/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package com.nch.mathracing;

import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

public class MathRacing extends BaseGameActivity{
	
	static Context mContext;
	static MathRacing myActivity;
	static int numSubmitScore = 0;
	private static final String LEADER_BOARD_ID = "CgkIhaK4lqIYEAIQBw";
	static AdView adView;
	
    protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);	
		
		mContext = MathRacing.this;
		myActivity = this;

		adView = new AdView(mContext);
	    adView.setAdSize(AdSize.BANNER);
	    adView.setAdUnitId("a1534430ec6fdf0");
	    adView.setBackgroundColor(Color.TRANSPARENT);		// have to have this line, ad may be visible
	    
	    RelativeLayout layout = new RelativeLayout(this);
	    
	    RelativeLayout.LayoutParams childParams = new RelativeLayout.LayoutParams(320, 50);
	    childParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
	    layout.addView(adView, childParams);

	    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, 
	    		RelativeLayout.LayoutParams.FILL_PARENT);
	    this.addContentView(layout, params);
	    
	    /*RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
	             getWindowManager().getDefaultDisplay().getWidth(),                        
	              LinearLayout.LayoutParams.WRAP_CONTENT);
	    adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
	    addContentView(adView, adParams);*/
	    
	    AdRequest adRequest = new AdRequest.Builder()
//	    .addTestDevice("EEB3EC34691D85EFD1DF789EA3776326")
	    .build();
		adView.loadAd(adRequest);
		
		ConnectivityManager connect =  (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		if(connect.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
				|| connect.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED){
			if(((MathRacing)mContext).getGamesClient().isConnected() == false){
				gameServicesSignIn();
			}
		}
		else{
			Toast.makeText(MathRacing.this, R.string.alert_turn_on_internet, Toast.LENGTH_LONG).show();
		}
	}

    public Cocos2dxGLSurfaceView onCreateView() {
    	Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
    	// MathRacing should create stencil buffer
    	glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
    	
    	return glSurfaceView;
    }

    static {
        System.loadLibrary("cocos2dcpp");
    }

	@Override
	public void onSignInFailed() {
	}

	@Override
	public void onSignInSucceeded() {
	}
	
	public static void gameServicesSignIn() {
		Log.i("", "gameServicesSignIn");
        ((MathRacing)mContext).runOnUiThread(new Runnable() {
            public void run() {
                ((MathRacing)mContext).beginUserInitiatedSignIn();
            } 
        });

    }
	
	public static void updateTopScoreLeaderboard(int score) {
    	Log.i("", "updateTopScoreLeaderboard " + score);
    	
    	ConnectivityManager connect =  (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		if(connect.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
				|| connect.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED){
			if(((MathRacing)mContext).getGamesClient().isConnected()){
				Log.i("", "updateTopScoreLeaderboard submit");
				((MathRacing)mContext).getGamesClient().submitScore(LEADER_BOARD_ID, score);
			}
			else{
				gameServicesSignIn();
			}
		}
		else{
			if(numSubmitScore % 10 == 0)
				((MathRacing)mContext).runOnUiThread(new Runnable() {
		            public void run() {
		            	Toast.makeText(mContext, R.string.alert_turn_on_internet, Toast.LENGTH_LONG).show();
		            }
		        });	
		}
		numSubmitScore++;
    }
	
	public static void showLeaderboards() {
    	ConnectivityManager connect =  (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		if(connect.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
				|| connect.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED){
			if(((MathRacing)mContext).getGamesClient().isConnected()){
				Log.i("", "showLeaderboards submit");
		        ((MathRacing)mContext).runOnUiThread(new Runnable() {
		            public void run() {
		                ((MathRacing)mContext).startActivityForResult(((MathRacing)mContext).getGamesClient().getLeaderboardIntent(LEADER_BOARD_ID), 5001);
		            }
		        });
			}
			else{
				gameServicesSignIn();
			}
		}
    }
	
	public static void rateApp() {
    	Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.nch.mathracing"));
		myActivity.startActivity(intent);
    }
	
	public static void hideAd() {
		myActivity.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				adView.setVisibility(View.INVISIBLE);
			}
		});
		
	}
	
	public static void showAd() {
		myActivity.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				adView.setVisibility(View.VISIBLE);
			}
		});
	}
}
